package com.example.tvapp.MyWebView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.example.tvapp.URL_REGULARS.URL_RULES;

import java.util.ArrayList;
import java.util.List;

//自定义实现的webview，拦截系统选中菜单并显示自定义的内容
/*
* 在布局文件中的使用：
*  <com.example.readerapp.MyWebView.MyWebView
            android:id="@+id/wv_webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"
    />
*
* */
public class MyWebView extends WebView
{
    Context context=this.getContext();
    WebView myWebView=this;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg)
        {
            switch ((msg.what))
            {

            }
        }
    };

    public MyWebView(@NonNull Context context)
    {
        super(context);
        linkJSInterface();


    }
    /*必须实现下面的构造方法*/
   public MyWebView(Context context, AttributeSet attrs)
   {

       super(context, attrs);
       linkJSInterface();

   }
    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {

       super(context, attrs, defStyleAttr, 0);
        linkJSInterface();
    }


    /*覆写View.class的方法*/
    @Override
    public ActionMode startActionMode(ActionMode.Callback callback)
    {
        //callback=myCallback;
        ActionMode actionMode=super.startActionMode(callback);
       return resolveItem(actionMode);
       // return actionMode;
    }
    @Override
    public ActionMode startActionMode(ActionMode.Callback callback, int type){
      //  callback=myCallback;
        ActionMode actionMode =  super.startActionMode(callback, type);
         return resolveItem(actionMode);
        //return actionMode;
    }


    ActionMode temp=null;
    private  ActionMode resolveItem(ActionMode actionMode)
    {
        if(actionMode!=null)
        {
            temp=actionMode;
            Menu menu=actionMode.getMenu();//这个好像是选中文本之后弹出的框子里面的元素的菜单
            menu.clear();//清空系统的弹出框的元素
            //随便往弹出的菜单加点东西
            List<Integer> actionList=new ArrayList<>();
            menu.add("复制");
            //定义点击事件
            WebView webView=this;
            for(int i=0;i<menu.size();i++)
            {
                MenuItem menuItem = menu.getItem(i);
                menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
                {
                    @Override
                    public boolean onMenuItemClick(@NonNull MenuItem item)
                    {
                        //得到的就是menu添加的标题名称
                        String title=item.getTitle().toString();
                        if(title.equals("翻译"))
                        {
                            selectedAndTranslate();
                        }
                        else if(title.equals("复制"))
                        {
                            copySelected();
                        }
                        //不加这个点击点击之后仍是选中状态
                        if(temp!=null)
                        {
                            temp.finish();
                            temp=null;
                        }
                        return true;
                    }
                });
            }

        }
        return actionMode;
    }
    /**
     * 点击的时候，获取网页中选择的文本，回掉到原生中的js接口
       */
    private void selectedAndTranslate() {


        //结尾要带分号
        //有比较大的概率获取不到文本
        String js = "(function getSelectedText() {" +
                 "try{" +
                /*"var txt=\"\";" +
                "if (window.getSelection) {" +
                "txt = window.getSelection().toString();" +
                "} else if (window.document.getSelection) {" +
                "txt = window.document.getSelection().toString();" +
                "} else if (window.document.selection) {" +
                "txt = window.document.selection.createRange().text;" +
                "};console.log(txt);" +
                "if(txt==undefined||txt==null||txt==\"\") alert(\"#\"+txt+\"#\"+selectedText+\"#\");"*/
                "try{/*myJSInterface.callback(selectedText)*/}catch(e){alert(e.toString)};"+
                "getTranslateFromBaiduAndShowWithPopup(selectedText);selectedText=\"\"" +//函数和selectedText变量(通过注册selectchanging监听器获取文本，还是有概率无法获取到选中的文本)在lookbook.html中定义
                ";" +
                "}catch(e){alert(e.toString())}" +
                "})()";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {  //android系统4.4以上的时候调用js方法用这个
            evaluateJavascript("javascript:" + js, null);
        } else {
            loadUrl("javascript:" + js);
        }
    }
    /**
     * 复制选中的文本
     * */
    private void copySelected()
    {
        String js = "(function getSelectedText() {" +
                "var txt;" +
                "if (window.getSelection) {" +
                "txt = window.getSelection().toString();" +
                "} else if (window.document.getSelection) {" +
                "txt = window.document.getSelection().toString();" +
                "} else if (window.document.selection) {" +
                "txt =selectedText;" +
                "};document.execCommand(\"Copy\");" +
                ";" +
                "})()";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {  //android系统4.4以上的时候调用js方法用这个
            evaluateJavascript("javascript:" + js, null);
            Toast.makeText(this.getContext(),"复制成功",Toast.LENGTH_SHORT).show();

        } else {
            loadUrl("javascript:" + js);
            Toast.makeText(this.getContext(),"复制成功",Toast.LENGTH_SHORT).show();
        }
    }


    //调用此函数为前端添加一个js函数，可通过此函数与webview交互
    //函数名称为第二个参数
    //函数参数与注解的函数的参数一致
    //前端使用：
    //myTTS.callback("回调参数")
    //必须在webview的构造函数中使用
    @SuppressLint("JavascriptInterface")
    private void linkJSInterface()
    {
        addJavascriptInterface(new Object(){

            @JavascriptInterface
            public void callback(String url,String title,String beizhu){
                try
                {
                    System.out.println("接收到:URL:"+url+"备注："+beizhu+"标题："+title);
                    URL_RULES.addCOLLECTS(url+"", title+"", beizhu+"");

                }catch (Exception e)
                {
                    //Toast.makeText(context,-12+"StartMyTTS\n"+e.toString(),Toast.LENGTH_SHORT).show();
                }
            }

        },"uploadCollect");

    }


}
